<template>
  <div class="detail-container">
    <el-form
      ref="postForm"
      :rules="rules"
      :model="postForm" 
      label-width="90px" 
      label-position="right"
      v-loading="fetchLoading"
    >
      <el-form-item label="所属角色" prop="role_id">
        <el-select
          size="medium" 
          v-model="postForm.role_id"
          placeholder="请选择所属角色" 
          :loading="roleLoaidng"
        >
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.name"
            :value="item.id" 
            :disabled="item.is_super == 1" 
          />
        </el-select>
      </el-form-item>
      <el-form-item label="登陆账号" prop="account">
        <el-input v-model="postForm.account" placeholder="请填写登录账号 仅支持英文字母"></el-input>
      </el-form-item>
      <template v-if="!update">
        <el-form-item label="登陆密码" prop="password">
          <el-input v-model="postForm.password" placeholder="请设置登录密码 必须字母与数字组合"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPassword">
          <el-input v-model="postForm.checkPassword" placeholder="请再次输入登录密码"></el-input>
        </el-form-item>
      </template>
      <el-form-item label="绑定手机" prop="bind_phone">
        <el-input v-model="postForm.bind_phone" placeholder="请设置绑定手机"></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="postForm.nickname" placeholder="请填写昵称"></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="image_id">
        <cover-upload 
          :cover="postForm.image"
          :max-length="1" 
          :switchFix="false" 
          dir-name="avatar" 
          @choose="onCoverChoose"
        />
        <el-input v-model="postForm.image_id" v-show="false"></el-input>
      </el-form-item>
      <el-form-item label="账号状态">
        <el-radio-group v-model="postForm.status">
          <el-radio :label="0">正常</el-radio>
          <el-radio :label="1">冻结</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary" 
          :loading="saveLoading"
          @click.native.prevent="handleSave"
        >{{ update ? '确认更新' : '确认新增' }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { managerInfo, managerCreate, managerUpdate } from '@/api/manager'
import { roleList } from '@/api/role'
import { validatePhone, validateExternal } from '@/utils/validate'
import CoverUpload from '@/components/CoverUpload'

const defaultForm = {
  role_id: null,
  account: '',
  password: '',
  checkPassword: '',
  bind_phone: '',
  nickname: '',
  image: null,
  image_id: 0,
  status: 0,
}

export default {
  name: 'ManagerDetail',
  components: { CoverUpload },
  props: {
    update: { // 是否编辑
      type: Boolean,
      default: false,
    },
    id: [String, Number], // id 编辑时传递
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (this.postForm.checkPassword !== '') {
        this.$refs.postForm.validateField('checkPassword')
      }
      callback()
    };
    const validatePass2 = (rule, value, callback) => {
      if (value !== this.postForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      postForm: {},
      fetchLoading: false,
      saveLoading: false,
      rules: {
        role_id: [
          { required: true, message: "请选择角色", trigger: "change" },
          { type: 'integer', message: "角色格式不正确", trigger: "change" },
        ],
        account: [
          { required: true, message: "请设置账号", trigger: "blur" },
          { min: 5, max: 18, message: '长度在 5 到 18 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: "请设置密码", trigger: "blur" },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' },
          { validator: validatePass, trigger: "blur" },
        ],
        checkPassword: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          { validator: validatePass2, trigger: "blur" },
        ],
        bind_phone: [
          { required: true, message: "请设置绑定手机", trigger: "blur" },
          { validator: validatePhone, trigger: "blur" },
        ],
        nickname: [
          { required: true, message: "请设置昵称", trigger: "blur" },
          { min: 1, max: 12, message: '长度在 1 到 18 个字符', trigger: 'blur' },
        ],
        avatar: [
          { required: true, message: "请上传头像", trigger: "blur" },
          { validator: validateExternal, trigger: "blur" },
        ],
        image_id: [
          { required: true, message: "请上传头像", trigger: "change" },
          { type: 'integer', message: "头像格式不正确", trigger: "change" },
        ],
      },
      roleLoaidng: false,
      roleList: [],
    }
  },
  created() {
    if (this.update) {
      this.getManagerInfo()
    } else {
      this.postForm = Object.assign({}, defaultForm)
    }
    this.getRoleList()
  },
  methods: {
    // 详情
    async getManagerInfo() {
      try {
        this.fetchLoading = true
        const { info } = await managerInfo(this.id)
        this.postForm = info
        this.postForm.checkPassword = ''
      } finally {
        this.fetchLoading = false
      }
    },
    // 获取角色列表
    async getRoleList() {
      try {
        this.roleLoaidng = true
        const { data } = await roleList()
        this.roleList = data
      } finally {
        this.roleLoaidng = false
      }
    },
    // 头像选择
    onCoverChoose(info) {
      this.postForm.image = info
      this.postForm.image_id = info.id
    },
    // 保存、修改
    handleSave() {
      this.$refs.postForm.validate(async valid => {
        if (!valid) return
        try {
          this.saveLoading = true
          if (this.update) {
            await managerUpdate(this.postForm)
            this.$notify.success({
              title: '成功',
              message: '更新成功',
              duration: 3000,
            });
            this.$router.go(-1)
          } else {
            await managerCreate(this.postForm)
            this.$notify.success({
              title: '成功',
              message: '新增成功',
              duration: 3000,
            });
            this.$refs.postForm.resetFields()
            this.postForm = Object.assign({}, defaultForm)
          }
        } finally {
          this.saveLoading = false
        }
      })
    }
  },
}
</script>

<style lang="scss" scoped>

</style>